package com.ctcemti.mdm.common.util;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * @ClassName BatchOperationUtils
 * @Description 批量处理类
 * @Author bxf
 * @Date 9:13 2019/7/26
 * @Version V1.0
 **/
@Slf4j
public class BatchOperationUtils<T> {




    /* *
     * @Author bxf
     * @Description
     * @Date 9:13 2019/7/26
     * @param list 插入数据
     * @param remark 每组
     * @param function 实现方法
     * @return java.lang.Object
     */
    public Object batchOperation(List<T> list, Integer remark, Consumer<List<T>> function){
        if(remark==null){
            remark = 100;
        }
        int size = list.size()%remark==0?list.size()/remark:(list.size()/remark)+1;
        List<Object> resultlist = new ArrayList<Object>();
        for (int j=0;j<size;j++){
            List<T> templist = null;
            if(j==size-1){
                templist = list.subList(j*remark,list.size());
            }else{
                templist = list.subList(j*remark,(j+1)*remark);
            }

            function.accept(templist);


        }
        return  resultlist;
    }

    /* *
     * @Author bxf
     * @Description
     * @Date 9:13 2019/7/26
     * @param list 查询数据
     * @param remark 每组
     * @param params 参数
     * @param function 实现方法
     * @return java.lang.Object
     */
    public Object batchOperation(List<T> list, Integer remark, Map<String,Object> params, Function<Object, Object> function){
        if(remark==null){
            remark = 100;
        }
        int size = list.size()%remark==0?list.size()/remark:(list.size()/remark)+1;
        List<Object> resultlist = new ArrayList<Object>();
        for (int j=0;j<size;j++){
            List<T> templist = null;
            if(j==size-1){
                templist = list.subList(j*remark,list.size());
            }else{
                templist = list.subList(j*remark,(j+1)*remark);
            }
            params.put("list",templist);
            Object out = function.apply(params);
            if(out instanceof List){
                resultlist.addAll((Collection<?>) out);
            }else{
                resultlist.add(out);
            }
        }
        return  resultlist;
    }


}
